<template>
  <div class="app-container">
    <el-card>
       <el-form :model="queryParam" ref="queryForm" :inline="true" >  
      <el-form-item label="学科：" >
        <el-select v-model="queryParam.subject" style="width:100px">
          <el-option label="数学" value="1" />
          <el-option label="物理" value="2" />
        </el-select>
      </el-form-item>
       <el-form-item label="题目：" >
        <el-input v-model="queryParam.content" clearable ></el-input>
      </el-form-item>
      <el-form-item label="标签：">
        <el-input v-model="queryParam.tag" clearable ></el-input>
      </el-form-item>
       <el-form-item label="答题：">
        <el-select v-model="queryParam.status" style="width:100px">
          <el-option label="未答题" value="0"/>
          <el-option label="已答题" value="1" />
          <el-option label="全部" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitSearch">查询</el-button>
      </el-form-item>
    </el-form>
      <!--用户列表区域-->
    <el-table v-loading="listLoading" :data="tableData" :cell-style="cellStyle" style="width: 100%" border stripe>
        <el-table-column prop="id" label="#" width="60px"></el-table-column>
        <el-table-column prop="subject" label="学科" :formatter="subjectFormatter" width="80px"></el-table-column>
        <el-table-column  label="题目">
          <template slot-scope="scope">
            <p v-html="scope.row.content"></p>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="分数" width="60px"></el-table-column>
        <el-table-column prop="status" label="状态" :formatter="selectFormatter" width="80px">  
        </el-table-column>
        <el-table-column prop="auth" label="作者" width="80px"></el-table-column>
        <el-table-column prop="time" label="创建时间" width="100px"></el-table-column>  
        <el-table-column label="操作" width="210px">
          <template slot-scope="scope">
                   <el-button @click="showQuestionDialog(scope.row)"  type="primary" icon="" size="mini">修改</el-button>
                    <!--修改按钮-->
                    <el-tooltip  effect="dark" content="答题" placement="top" :enterable="false">
                    <el-button @click="showEditDialog(scope.row)"  type="primary" icon="" size="mini">答题</el-button>
                    </el-tooltip>                  
                    <!--删除按钮-->
                    <el-tooltip  effect="dark" content="删除" placement="top" :enterable="false">
                        <el-button type="danger" @click="deleteQuestion(scope.row)" icon="" size="mini">删除</el-button>
                    </el-tooltip>
                </template>
        </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParam.pageIndex"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryParam.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
      </el-pagination>
      <el-dialog
            title="修改题目"
            :visible.sync="addDialogVisible" @opened="show1('#questionEditor')" @closed="hide()"
            width="50%" @close="addDialogClosed">
            <!--内容主体区域-->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px" >
                <el-form-item label="题目：" prop="question">
                    <!--<el-input v-model="editForm.answer"></el-input>-->
                    <div id="questionEditor"></div>
                </el-form-item>
            </el-form>
            <!--底部区域-->
            <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editQuestion">确 定</el-button>
            </span>
        </el-dialog>
      <el-dialog
            title="答题"
             v-draggable
            :visible.sync="editDialogVisible" @opened="show('#answerEditor')" @closed="hide()"
            width="60%" @close="editDialogClosed">
            <!--内容主体区域-->
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px" >
                <el-form-item label="题目：">
                     <p v-html="editForm.content"></p>
                </el-form-item>
                <el-form-item label="答题：" prop="answer">
                    <!--<el-input v-model="editForm.answer"></el-input>-->
                    <div id="answerEditor"></div>
                </el-form-item>
                <el-form-item label="考点：" prop="summary">
                    <el-input v-model="editForm.summary" type="textarea"></el-input>
                </el-form-item>
                <el-form-item label="分数：" prop="score">
                  <el-input-number v-model="editForm.score" @change="handleChange" :min="1" :max="30" label="分数"></el-input-number>
                </el-form-item>
            </el-form>
            <!--底部区域-->
            <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editAnswer">确 定</el-button>
            </span>
        </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from "vuex";

import WangEditor from 'wangeditor'
import createKityformula from './components/kityformula'
import myscriptMath from './components/myscript-math-web'
import { QuestionList,updateQuestion,updateAnswer, deleteQuestion} from '@/api/examApi.js'

import {Base64} from 'js-base64'


export default {
  data() {
    var checkEmail = (rule,value,cb) =>{
            const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
            if(regEmail.test(value)){
                //合法的邮箱
                return cb()
            }
            cb(new Error("请输入合法的邮箱"))
        }
        //验证手机号码的规则
        var checkMobile = (rule,value,cb) =>{
            const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/ 
            if (regMobile.test(value)) { 
                //合法的手机号码
                return cb() 
            }
            cb(new Error('手机号码格式不正确'))     
        }
      const validateAnswer = (rule, value, callback) => {
        if (this.editor.txt.html().length < 4) {
          callback(new Error('The password can not be less than 6 digits'))
        } else {
          callback()
        }
      }

        return{
            //获取用户列表的参数对象
            queryParam: {
                subject:'1',
                content:'',
                tag: '',
                status:'2',
                //当前页数
                pageIndex: 1,
                //当前页数据个数
                pageSize: 10,
                auth: ''
            },
            tableData:[],
            total: 0,
            addDialogVisible: false,
            addForm: {
                id:'',
                content: '',
            },
            //控制修改用户的对话框的显示与隐藏
            editDialogVisible :false,       
            editForm: {
              id:'',
              content:'',
              answer:'',
              summary:'',
              score:'',
              testtxt:''
            },
             addFormRules: {
               question: [
                    {required: true,message: '请输入题目内容',trigger: 'blur',validator:validateAnswer}     
                ],
            },
            //修改表单的验证规则对象
            editFormRules: {
                answer: [
                    {required: true,message: '请输入答题内容',trigger: 'blur',validator:validateAnswer}     
                ],
                mobile: [
                    {required: true,message: '请输入手机号码',trigger: 'blur'},
                    {validator: checkMobile, trigger: 'blur'}
                ],
                tag: [
                    { required: true, message: '请输入考点说明', trigger: 'blur' }
                  ]
            },
            editor:null,
            baseUrl: process.env.VUE_APP_BASE_API + '/math/uploadfiles.aspx',
        }
  },
  created () {
    //this.formatMath()
    this.search()
  },
  mounted () {
   //this.createEditor()
  },
  methods: {
    createEditor(id){
         const editor = new WangEditor(id)

    // 配置菜单栏，删减菜单，调整顺序
    // editor.config.menus = ['bold', 'head', 'link', 'italic', 'underline']

    // 配置行高
    // editor.config.lineHeights = ['1', '1.15', '1.6', '2', '2.5', '3']

    // 获取必要的变量，这些在下文中都会用到
    const { $ } = WangEditor
    const { PanelMenu, Panel } = WangEditor

    class Kityformula extends PanelMenu {
      // 公式输入插件
      constructor (editors) {
        const $elem = WangEditor.$(
          `<div class="w-e-menu">公式</div>`
        )
        super($elem, editors)
      }

      // 菜单点击事件
      clickHandler () {
        // 做任何你想做的事情
        // 可参考【常用 API】文档，来操作编辑器
        const conf = createKityformula(editor)
        const panel = new Panel(this, conf)
        panel.create()
      }

      tryChangeActive () {}
    }

    class Myscript extends PanelMenu {
      // 公式手写插件
      constructor (editors) {
        const $elem = WangEditor.$(
          `<div class="w-e-menu">手写</div>`
        )
        super($elem, editors)
      }

      // 菜单点击事件
      clickHandler () {
        // 做任何你想做的事情
        // 可参考【常用 API】文档，来操作编辑器
        const conf = myscriptMath(editor)
        const panel = new Panel(this, conf)
        panel.create()
      }

      tryChangeActive () {}
    }

    // 注册菜单
    const kityformulaKey = 'kityformulaKey' // 菜单 key ，各个菜单不能重复
    editor.menus.extend('kityformulaKey', Kityformula)

    // 注册菜单
    const myscriptKey = 'myscriptKey' // 菜单 key ，各个菜单不能重复
    editor.menus.extend('myscriptKey', Myscript)

    // 将菜单加入到 editor.config.menus 中
    // 也可以通过配置 menus 调整菜单的顺序，参考【配置菜单】部分的文档
    editor.config.menus = editor.config.menus.concat(kityformulaKey)
    editor.config.menus = editor.config.menus.concat(myscriptKey)

    editor.config.uploadImgShowBase64 = false
    editor.config.uploadImgMaxLength = 5 // 一次最多上传 5 个图片

    editor.config.showLinkImg  = false   //隐藏插入网络图片的功能
    editor.config.uploadImgServer = this.baseUrl
    editor.config.uploadImgHooks = {
      onSuccess : function(xhr, editor, result) { 
        console.log("上传成功"); 
      },
      fail : function(xhr, editor, result) {
         console.log("上传失败,原因是"+result);
      },
      error : function(xhr, editor) { 
        console.log("上传出错");
      },
      customInsert:function(insertImgFn,resutl){ 
        for(var j = 0;j < resutl.data.length;j++){
          //alert(JSON.stringify(resutl.data[j]))
          insertImgFn(resutl.data[j].url)
        }
      }
    }

    // 配置 onchange 回调函数，将数据同步到 vue 中
    editor.config.onchange = newHtml => {

      //this.editorData = newHtml
      //console.log(this.editorData)
    }
    // 创建编辑器
    editor.create()
    this.editor = editor
    },
    submitSearch() {
       //alert(this.queryParam.subjectId)
       //this.$message('查询!')
       this.queryParam.pageIndex = 1
       this.search()
    },
    search () {
      let _this = this;
      _this.listLoading = true
      //alert(rank)
      //alert(username)  
     // alert(JSON.stringify(this.queryParam))
       if (_this.rank<10){
        _this.queryParam.auth = _this.username;
      }
      QuestionList(_this.queryParam).then(response => {
        //alert(JSON.stringify(response))
        const re = response   
        _this.tableData = re.data
        _this.total = re.totalrecord
        _this.queryParam.pageIndex = re.curpage
        _this.listLoading = false
      })
    },
    //监听 pagesize 改变的事件
    handleSizeChange(newSize){
      //console.log(newSize)
      this.queryParam.pagesize = newSize;
      this.search()
    },
    //监听页码值改变的事件
    handleCurrentChange(newPage){
        //console.log(newPage)
        //alert(newPage)
        this.queryParam.pageIndex = newPage;
        this.search()
    },
    showQuestionDialog(data){
      //this.createEditor()
      this.addForm.id = data.id
      this.addForm.content = data.content
      //alert(data.content)
      //alert((this.editForm.id))
      this.addDialogVisible = true
    },
    show1(id){
      let _this = this;
      _this.createEditor(id);
      _this.editor.txt.html(_this.addForm.content);

    },
    editQuestion(){
      let _this = this
      const myData = this.editor.txt.html();
      var myText = Base64.encode(myData);
      //alert(myText.length)
      this.$refs.addFormRef.validate( async valid=>{
                //alert(valid)
                if(!valid) return
                //可以发起修改用户的请求
               // const {data:res} = await this.$http.put('users/' + this.editForm.id,{
                //    email: this.editForm.email , mobile: this.editForm.mobile
                //})
                //console.log(res)
                //if(res.meta.status !== 200) return this.$message.error('更新用户信息失败!')
                var jsData = {"id":_this.addForm.id,"content":myText}
                //alert(JSON.stringify(jsData))
                await updateQuestion(jsData).then(response => {
                  if (response.code === 200) {
                    //_this.search()
                     _this.$message.success(response.message)
                     } else {
                       //_this.$message.error(re.message)
                      }
               })         
                //隐藏添加用户的对话框
                _this.addDialogVisible = false
                //刷新数据列表
                //this.search()
                //提示修改成功
                //this.$message.success('更新用户信息用户成功!')
            })


    },
    show(id){
      let _this = this;
      _this.createEditor(id);
      _this.editor.txt.html(_this.editForm.testtxt);

    },
    hide(){
      this.editor.destroy();
      this.editor = null;
    },
    showEditDialog(data){
      //this.createEditor()
      this.editForm.id = data.id
      this.editForm.content = data.content
      this.editForm.summary = data.summary
      this.editForm.score = data.score
      //alert(data.answer)
      this.editForm.testtxt = data.answer
      this.editDialogVisible = true
    },
    editAnswer(){
      let _this = this
      const myData = this.editor.txt.html();
      var myText = Base64.encode(myData);
      this.$refs.editFormRef.validate( async valid=>{
                //alert(valid)
                if(!valid) return
                //可以发起修改用户的请求
               // const {data:res} = await this.$http.put('users/' + this.editForm.id,{
                //    email: this.editForm.email , mobile: this.editForm.mobile
                //})
                //console.log(res)
                //if(res.meta.status !== 200) return this.$message.error('更新用户信息失败!')
                var jsData = {"id":_this.editForm.id,"answer":myText, "summary":_this.editForm.summary,"score":_this.editForm.score}
                //alert(JSON.stringify(jsData))
                await updateAnswer(jsData).then(response => {
                  if (response.code === 200) {
                    _this.search()
                     _this.$message.success(response.message)
                     } else {
                       //_this.$message.error(re.message)
                      }
               })         
                //隐藏添加用户的对话框
                _this.editDialogVisible = false
                //刷新数据列表
                //this.search()
                //提示修改成功
                //this.$message.success('更新用户信息用户成功!')
            })
    },
    deleteQuestion (row) {
      let _this = this
      var jsData={"id":row.id}
      //alert(JSON.stringify(jsData))
      deleteQuestion(jsData).then(re => {
        if (re.code === 200) {
          _this.search()
          _this.$message.success(re.message)
        } else {
          _this.$message.error(re.message)
        }
      })
    },
    cellStyle ({row, column, rowIndex, columnIndex }) {
      if (row.status === 1 && columnIndex === 4) {
        return 'color: #0CB618'
      } else if (row.status === 0 && columnIndex === 4) {
        return 'color: #EA1B29'
      } else {
        return 'color: #1a1a1b'
      }
    },
    subjectFormatter (row, column, cellValue, index) {
        if (cellValue == '1'){
            return '数学'
        }else if (cellValue == '2'){
            return '物理'
        }
    },
    selectFormatter (row, column, cellValue, index) {
        if (cellValue == 0){
            return '未答题'
        }else if (cellValue == 1){
            return '已答题'
        }
    },
    onSubmit() {
      this.$message('submit!')
    },
    onCancel() {
      this.$message({
        message: 'cancel!',
        type: 'warning'
      })
    }
  },
  computed: {
    ...mapGetters({username:"name", score:"score",rank:"rank" }),
    classObje(totalGrade) {           
      return (totalGrade) => { 
        if (totalGrade <0){
          return {'color':'#13ce66'}  
        } else if (totalGrade === 0){
          return {'color':'#000000',}
        } else if (totalGrade >0){
          return {'color':'red',}
        }      
      }
    }
  },
}
</script>

<style scoped>
.line{
  text-align: center;
}
.font-class-red {
    color: red !important;
  }
  .font-class-green {
    color: green !important;
  }
  .font-class-yellow {
    color:yellow !important;
  }
</style>

